import React, {Component} from 'react';
import {Platform,System,BackHandler,Alert,ToastAndroid, StatusBar,StyleSheet, TouchableOpacity,TextInput,Text,Image,Button,View} from 'react-native';
import TabNavigator from 'react-native-tab-navigator';
import Toast from 'react-native-root-toast'; 
import map from './map';
import check from './check';
import mine from './mine';
import doctor from './doctor';
import record from './record';
import {connect,Provider,applyMiddleware} from 'react-redux';
import { NavigationActions } from 'react-navigation';
import RNExitApp from 'react-native-exit-app';





export const TAB = {
    Map: 'Map',
    Check: 'Check',
    Mine: 'Mine',
    Doctor: 'Doctor',
    Record:'Record'

}

class mainPage extends Component{

    constructor(props){
        super(props);
        this.state={
            selectTab:"Check",
        }
        this.onBackAndroid=this.onBackAndroid.bind(this);
        this._testVersionShow=this._testVersionShow.bind(this);

    }

    static navigationOptions = {
     header:null,
     
        gesturesEnabled:false  // 是否可以右滑返回
  
    };

    componentDidMount() 
    {
        if (Platform.OS === 'android') {
            BackHandler.addEventListener('hardwareBackPress', this.onBackAndroid);
        }

    };
    componentWillMount()
    {
        if (Platform.OS === 'android') {
            BackHandler.removeEventListener('hardwareBackPress', this.onBackAndroid);
        }

    };

    onBackAndroid = () => {

        
        console.log("ONBack");
        console.log(this.props);
        if(this.props.Nav.index==0)
        {
            if (this.lastBackPressed && this.lastBackPressed + 2000 >= Date.now()) {
                //最近2秒内按过back键，可以退出应用。
                //RNExitApp.exitApp();
                RNExitApp.exitApp();

                //BackHandler.exitApp();

                //System.exit(0);
                //return false;
              }
              this.lastBackPressed = Date.now();
            //   
            Toast.show("再按一次退出");
              return true;

        }else
        {
            this.props.dispatch(NavigationActions.back())
            return true;
        }
       
       
        // const {routes} = this.props;
       
       
        // if (routers.length > 1) {
        // nav.pop();
        // return true;
        // }
        // return false;
    };


    _onSelected(tap){

        this.setState({selectTab:tap});
    }


  _testVersionShow(tab){

    if(tab=="Doctor"||tab=="Record")
    {
        Toast.show("内测版功能暂未开放,请等待正式版");
    }else{
        //Toast.show(title);
       // console.log(title);
        
        this._onSelected(tab);
    }


  }

     _renderTab(Component,tab,title,icon){
        return (
            <TabNavigator.Item
                selected={this.state.selectTab === tab}
                title={title}
                titleStyle={styles.titleStyle}
                selectedTitleStyle={styles.selectedTitleStyle}//选中时tap的风格

                renderIcon={() => <Image style={[styles.tabItemImageStyle,{tintColor:'#AAAAAA'}]} source={icon}/>}

                renderSelectedIcon={() => <Image style={[styles.tabItemImageStyle,{tintColor:'white'}]} source={icon}/>}

                onPress={
                          ()=>{ this._testVersionShow(tab)}
                        }
                        >
                <Component {...this.props}  homeComponent={this}/>
            </TabNavigator.Item>
        )

    }

    render(){
      
        return <View style={styles.container}>
                    <StatusBar  
                        animated={true} //指定状态栏的变化是否应以动画形式呈现。目前支持这几种样式：backgroundColor, barStyle和hidden  
                        hidden={false}  //是否隐藏状态栏。  
                        backgroundColor={'rgba(30,70,125,0.3)'} //状态栏的背景色  
                        translucent={true}//指定状态栏是否透明。设置为true时，应用会在状态栏之下绘制（即所谓“沉浸式”——被状态栏遮住一部分）。常和带有半透明背景色的状态栏搭配使用。  
                        barStyle={'light-content'} // enum('default', 'light-content', 'dark-content')   
                        >  
                     </StatusBar>  
                    <TabNavigator 
                    tabBarStyle={{height:50,opacity: 1,backgroundColor: 'rgb(30,70,125)'}}//'rgb(42,85,141)'
                    sceneStyle={{paddingBottom: 0}}>
                   
                    {this._renderTab(map,TAB.Map,"附近仪器",require('../../res/images/map.png'))}
                    {this._renderTab(check,TAB.Check,"健康检测",require('../../res/images/check.png'))}
                    {this._renderTab(record,TAB.Record,"健康记录",require('../../res/images/record.png'))}
                    {this._renderTab(doctor,TAB.Doctor,"健康咨询",require('../../res/images/doctor.png'))}
                    {this._renderTab(mine,TAB.Mine,"我",require('../../res/images/mine.png'))}
                    </TabNavigator>
              </View>

    }

}

const styles = StyleSheet.create({
    container: {
      flex: 1,  
     // backgroundColor: 'rgb(69,122,173)',
     backgroundColor:'#f3f3f4',

    // backgroundColor: 'rgb(255,255,255)',

    },
    center:{
      alignItems:'center',
      justifyContent: 'center',
    }, 
    titleStyle:{
        color:'#AAAAAA',
        fontSize:10

    },
    selectedTitleStyle:{
        color:'rgb(255,255,255)',
        fontSize:12

    },
    tabItemImageStyle:{
        width:25,
        height:25
    }
});




function mapStateToProps(state){

    const {Net,Nav}=state;
    console.log(state);
    return {
          Net,
           Nav
     }

}



export default connect(mapStateToProps)(mainPage);
